<template>
  <div>
    <a-card title="员工业绩">
      <a-form-model ref="form" :model="searchForm" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
      <a-row gutter="24">
        <a-col :span="4" :md="8" :xl="6" style="padding-left: 0px; padding-right: 0px; width: 200px;margin-right: 0px;margin-left: 0px;">
              <a-form-model-item prop="is_void"  label="订单状态">
                <a-select v-model="searchForm.is_void" style="width: 100%" placeholder="订单状态" allowClear>
                  <a-select-option v-for="item in is_Void_Options" :key="item.id" :value="item.value">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>             
        </a-col>
        <a-col :span="4" :md="8" :xl="6" style="padding-left: 0px; padding-right: 0px; width: 200px;margin-right: 0px;margin-left: -10px;">
              <a-form-model-item prop="jgfl" label="分类">
                <a-select v-model="searchForm.jgfl" style="width: 100%" placeholder="分类" allowClear>
                  <a-select-option v-for="item in jgfltems" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
        </a-col>
        <a-col :span="4" style="padding-left: 0px; padding-right: 0px; width: 200px;margin-right: 0px;margin-left: 10px;">
              <a-form-model-item prop="client" label="加工人员" >
                <a-select showSearch v-model="searchForm.jgry" style="width: 100%" :filterOption="filterOption" allowClear>
                  <a-select-option v-for="item in jg_handlerItems" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
        <a-col :span="4" style="padding-left: 0px; padding-right: 0px; width: 200px;margin-right: 0px;margin-left: -10px;">
              <a-form-model-item prop="search" label="搜索" >
                <a-input v-model="searchForm.search" allowClear placeholder="单号/分类/客户/员工姓名" />
                <!-- <a-input v-model="searchForm.search" allowClear :placeholder="NewdateToString" /> -->
              </a-form-model-item>
        </a-col>
        <a-col :span="4" style="width: 300px;">
          <a-form-model-item label="开单日期" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-range-picker v-model="dateRange" @change="changeDate" style="width: 100%;" :ranges="ranges"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="6" style="padding-left: 0px; padding-right: 0px; width: 300px;margin-right: 0px;margin-left: 0px;">
            <a-form-model-item >
              <a-button-group> 
                <a-button type="primary" :loading="loading" @click="search"><a-icon type="search" />查询</a-button>    
                <a-button :loading="downloadLoading" @click="handleDownload"><a-icon type="file-excel" />导出</a-button>    
              </a-button-group>
            </a-form-model-item>
          </a-col>

        <!-- <a-col :span="24" :md="8" :xl="6" style="max-width: 256px; margin-bottom: 12px;">
          <a-range-picker @change="onChangePicker" />
        </a-col> -->
      </a-row>
    </a-form-model>
    <a-row style="margin-top: 0px;">
      查询结果-> 数据条数：共{{ total.count }}(条)，材料数量：{{ total.total_clsl }}(单位)，材料总金额：{{ total.total_clAmount }}(元)，加工数量：{{ total.total_jgsl }}(件)，加工总金额：{{ total.total_jgAmount }}(元)，总金额:{{ total.total_clAmount + total.total_jgAmount}}(元)
    </a-row>
      <a-row style="margin-top: 12px;">
        <a-table size="small" :columns="columns" :dataSource="items" rowKey="id" :loading="loading" :pagination="pagination" 
        style="width: 100%;"
          @change="tableChange">
          <div slot="is_void" slot-scope="value">
            <a-tag :color="get_tag_parm(value).color">{{ get_tag_parm(value).status}}</a-tag>
          </div>
          <div slot="qualification_status" slot-scope="value">
            <a-tag :color="get_tag_qualification_status(value).color">{{ get_tag_qualification_status(value).status}}</a-tag>
          </div>
          <div slot="action" slot-scope="value, item">
            <a-button-group size="small">
              <a-button size="small" @click="view(item)">查看详情</a-button>
            </a-button-group>
          </div>
            <!-- <template slot="footer">
              <template slot-scope="{ columns, items }">
                  <tr>
                    <td v-for="(column,index) in columns" :key="index">
                      <strong>合计</strong>
                    </td>
                    <td>{{ items.length }}</td>
                  </tr>
              </template>
          </template> -->
        </a-table>
        
      </a-row>
    </a-card>
  </div>
</template>

<script>
  import { saleOrderList, saleOrdersVoid } from '@/api/sale'
  import { datetimeToString} from "@/utils/common";
  import { List} from '@/api/common'
  import { clientsOption } from "@/api/option";
  import moment from 'moment'

  export default {
    name: 'SaleRecord',
    components: {
    },
    data() {
      return {
        ranges: {
        '今日': [moment().startOf('day'), moment().startOf('day')],
        '昨日': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        '本周': [moment().week(moment().week()).startOf('week'), moment().week(moment().week()).endOf('week')],
        '上周': [moment().subtract(1,'week').startOf('week'), moment().subtract(1,'week').endOf('week')],
        '本月': [moment().startOf('month'), moment().startOf('day')],
        '上月': [moment().subtract(1,'month').startOf('month'), moment().subtract(1,'month').endOf('month')],
       },
        columns: [
          {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            customRender: (value, item, index) => {
              return index + 1
            },
            width: 45
          },
          {
            title: '销售编号',
            dataIndex: 'salesOrder_number',
            width: 130
          },
          {
            title: '客户',
            dataIndex: 'salesOrder_client',
            width: 80
          },


          {
            title: '产品编号',
            dataIndex: 'goods_number',
            width: 125
          },
          {
            title: '产品名称',
            dataIndex: 'goods_name',
            width: 80
          },
          {
            title: '产品规格',
            dataIndex: 'guige',
            width: 80
          },
          {
            title: '材料数量',
            dataIndex: 'clsl',
            width: 80
          },
          {
            title: '材料单价',
            dataIndex: 'cldj',
            width: 80
          },
          {
            title: '材料金额',
            dataIndex: 'clAmount',
            width: 80
          },
          {
            title: '加工数量',
            dataIndex: 'jgsl',
            width: 80
          },
          {
            title: '加工金额',
            dataIndex: 'jgAmount',
            width: 90,
            sorter: true,
          },

          {
            title: '分类',
            dataIndex: 'jgfl_name',
            width: 60
          },
          {
            title: '加工人员',
            dataIndex: 'jgry_items',
            width: 120,
                customRender: (value, item, index) => {
                let roles=""
                value.forEach(e => {
                  roles+=e.name+"/"
                });
            return roles.slice(0,roles.length-1)
            },
          },
          {
            title: '订单状态',
            dataIndex: 'is_void',
            key: "is_void",
            width: 80,
            align:'center',
            scopedSlots: { customRender: "is_void" },   
          },
          {
            title: '经手人',
            dataIndex: 'salesOrder_handler',
            width: 60
          },
          {
            title: '处理时间',
            dataIndex: 'salesOrder_create_time',
            width: 150
          },
          // {
          //   title: '操作',
          //   dataIndex: 'action',
          //   scopedSlots: { customRender: 'action' },
          //   width: 200
          // },
        ],
        total:{
          count:0,
          total_clsl:0,
          total_clAmount:0,
          total_amount:0,
          collection_amount:0
        },
        // dateRange: [moment().startOf('day'), moment().startOf('day')],
        clientsItems: [],
        // dateRange: [moment().add(-100, 'days').startOf('day'), moment().startOf('day')],
        dateRange: [moment().startOf('day'), moment().startOf('day')],//获取本月开始第一天到今天
        searchForm: {
         page: 1, page_size: 15,is_void:false,search:null,
         jgfl:null,
         client:null,
        },
        pagination: { current: 1, total: 0, pageSize: 15 },
        loading: false,
        downloadLoading: false,
        downloadList: [],
        items: [],
        visible: false,
        targetItem: {},
        form: {},
        is_Void_Options:[
          {
            id:1,
            name:"所有",
            value:null
          },
          {
            id:2,
            name:"正常",
            value:false
          },
          {
            id:3,
            name:"已作废",
            value:true
          },
        ],
        jgfltems:[],
        jg_handlerItems: [],
      };
    },
    computed: {
      NewdateToString() {
            let ndate = new Date();
            var month = ndate.getMonth() + 1;
            var day = ndate.getDate();
            return (  
              (String(month).length > 1 ? month : "0" + month) +""+
              (String(day).length > 1 ? day : "0" + day) 
            );       
        },
        // 是否可以作废的标识
        is_void_may(){
          console.log(this.NewdateToString)
          // console.log(this.searchForm.search==this.NewdateToString)
          return this.searchForm.search==this.NewdateToString
        }
    },
    methods: {
        // 将输入的内容与显示的内容进行匹配
      filterOption (value, option) {
          return option.componentOptions.children[0].text.indexOf(value) >= 0
        },
      jgry_items2names(items){
          let names=""
          items.forEach(e => {            
            names +=e.name+"/"
          })
          return names.slice(0,names.length-1)
      },  
      getNewdownloadList(downloadList) {
          let o={
              index:'合计',
              clsl:0,
              clAmount:0,
              jgsl:0,
              jgAmount:0
          }
          downloadList.forEach(e => {
              e.jgry_items=this.jgry_items2names(e.jgry_items)
              e.is_void=e.is_void?'已作废':"正常"
          });
          if (downloadList) {
              let i=0
              downloadList.forEach(e => {
                  i+=1
                  e['index'] = i
                  o.clsl+=e.clsl
                  o.clAmount+=e.clAmount
                  o.jgsl+=e.jgsl
                  o.jgAmount+=e.jgAmount
              });
              downloadList.push(o)
          } else {
            downloadList = []
          }
      },
      handleDownload() {
        this.loading = true;
        this.downloadLoading = true;
        this.searchForm.start_date=this.dateRange.length > 0 ? this.dateRange[0].format('YYYY-MM-DD') : null
        this.searchForm.end_date=this.dateRange.length > 0 ? this.dateRange[1].format('YYYY-MM-DD') : null
        this.searchForm.page_size=9999
        if (this.searchForm.end_date) {
            this.searchForm.end_date = moment(this.searchForm.end_date).add(1, 'days').format('YYYY-MM-DD');
          }
          List(this.searchForm,'sales_SalesGoods').then(response  => {
          const resp = response.data;        
          this.downloadList = response.results;
          this.getNewdownloadList(this.downloadList) 
          // this.downloadList.forEach(e => {
          //     e.jgry_items=this.jgry_items2names(e.jgry_items)
          //     e.is_void=e.is_void?'已作废':"正常"
          // });
          // console.log('this.downloadList:',this.downloadList )
          this.searchForm.page_size=15
          import("@/vendor/Export2ExcelNew").then(excel => {
            const tHeader1 = [
              "序号",
              "销售编号",
              "客户",
              "产品编号",
              "产品名称",
              "产品规格",
              "材料数量",
              "材料单价",
              "材料金额",
              "加工数量",
              "加工金额",
              "分类",
              "加工人员",
              "订单状态",
              "经手人",
              "处理时间",
            ];
            const filterVal = [
              "index",
              "salesOrder_number",
              "salesOrder_client",
              "goods_number",
              "goods_name",
              "guige",
              "clsl",
              "cldj",
              "clAmount",
              "jgsl",
              "jgAmount",
              "jgfl_name",
              "jgry_items",
              "is_void",
              "salesOrder_handler",
              "salesOrder_create_time",
            ];
            //const filterVal = tHeader;
            //不要将下载数据与显示数据列表用同一个变量，否则要出问题
            const list = this.downloadList;
            let downloadList = list;
  
            const data = this.formatJson(filterVal, downloadList);
            console.log('data:',data)
            const title = ["员工业绩"+datetimeToString(new Date())];
            const sheetname = "员工业绩";
            const merges = [ "A1:P1"];
            excel.export_json_to_excel({
              title,
              header: tHeader1,
              // multiHeader:[tHeader1],            
              data,
              filename: "员工业绩"+datetimeToString(new Date()),
              merges,
              // autoWidth: this.autoWidth,
              autoWidth: this.autoWidth,
              bookType: this.bookType,
              sheetname
            });
            this.loading = false;
            this.downloadLoading = false;
          });
        });
      },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
      get_dict(){
        List({}, `dicts`).then((data) => {
          let res=data.results;
          this.jgfltems=res.filter(i=>i.code=='jgfltems')[0].dict_items    
        });
      },
      summary(){
        this.items.push(
          {
            number: '合计',
            arrears_amount: '',
            client_name: 1000,
            creator_name: '',
          }
        )
        console.log(this.items)
      },
      get_tag_parm(value){
        let color="green"
        let status="正常"
        if(value){
          color="red"
          status="已作废"
        }
        return{color,status}
      },
      get_tag_qualification_status(value){
        let color="red"
        let status="未付款"
        if(value){
          color="green"
          status="已付款"
        }
        return{color,status}
      },
      initialize() {
        List({ page_size: 999999, is_active: true},'users/options').then((data) => {
        this.jg_handlerItems=data.results.filter(i=>i.is_employee==true)
        console.log(this.jg_handlerItems)
      });
        this.get_dict();
        this.list();
      },
      list() {
        this.loading = true;
        this.searchForm.start_date=this.dateRange.length > 0 ? this.dateRange[0].format('YYYY-MM-DD') : null
        this.searchForm.end_date=this.dateRange.length > 0 ? this.dateRange[1].format('YYYY-MM-DD') : null
        if (this.searchForm.end_date) {
          this.searchForm.end_date = moment(this.searchForm.end_date).add(1, 'days').format('YYYY-MM-DD');
        }
        List(this.searchForm,'sales_SalesGoods').then(data => {
          this.pagination.total = data.count;
          this.total.count = data.count;
          this.total.total_clsl = data.total_clsl;
          this.total.total_clAmount = data.total_clAmount;
          this.total.total_jgAmount = data.total_jgAmount;
          this.total.total_jgsl = data.total_jgsl;
          this.items = data.results;
          // this.summary()
        }).finally(() => {
          this.loading = false;
        });
      },
      tableChange(pagination, filters, sorter) {
        this.searchForm.page = pagination.current;
        this.pagination.current = pagination.current;
        this.searchForm.ordering = `${sorter.order == 'descend' ? '-' : ''}${sorter.field}`;
        this.list();
      },
      onChangePicker(date, dateString) {
        let startDate = date[0], endDate = date[1];
        this.searchForm.start_date = startDate ? startDate.format('YYYY-MM-DD') : undefined;
        this.searchForm.end_date = endDate ? endDate.add(1, 'days').format('YYYY-MM-DD') : undefined;
        this.search();
      },
      search() {
        this.searchForm.page = 1;
        this.pagination.current = 1;
        this.list();
      },
      detial(item) {
        this.$router.push({ path: '/sale/sale_record_detail', query: { id: item.id } });
      },
      view(item) {
        this.$router.push({ path: '/sale/sale_record_view', query: { id: item.id } });
      },
      modify(item) {
        this.$router.push({ path: '/sale/sale_record_modify', query: { id: item.id } });
      },
      voidItem(item) {
        saleOrdersVoid({ id: item.id }).then(() => {
          this.$message.success('作废成功');
          this.searchForm.search=null
          this.list();
        });
      },
    },
    mounted() {
      this.initialize();
    },
  }
</script>